<template>
  <div class="merchant-management-container">
    <h2 class="page-title">商家管理</h2>
    
    <!-- 搜索和过滤 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="queryParams" class="filter-form">
        <el-form-item label="店铺名称">
          <el-input v-model="queryParams.shopName" placeholder="请输入店铺名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select v-model="queryParams.status" placeholder="请选择审核状态" clearable>
            <el-option label="待审核" :value="0"></el-option>
            <el-option label="已通过" :value="1"></el-option>
            <el-option label="已拒绝" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="营业状态">
          <el-select v-model="queryParams.businessStatus" placeholder="请选择营业状态" clearable>
            <el-option label="休息中" :value="0"></el-option>
            <el-option label="营业中" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 商家列表 -->
    <el-card class="table-card">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="全部商家" name="all"></el-tab-pane>
        <el-tab-pane label="待审核" name="pending">
          <span slot="label">待审核 <el-badge v-if="pendingCount > 0" :value="pendingCount" class="badge"></el-badge></span>
        </el-tab-pane>
        <el-tab-pane label="已通过" name="approved"></el-tab-pane>
        <el-tab-pane label="已拒绝" name="rejected"></el-tab-pane>
      </el-tabs>
      
      <el-table
        :data="merchantList"
        border
        stripe
        v-loading="loading">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column label="店铺信息" width="250">
          <template slot-scope="scope">
            <div class="merchant-info-cell">
              <div class="merchant-logo">
                <img :src="scope.row.shopLogo || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" alt="店铺Logo">
              </div>
              <div class="merchant-info">
                <div class="shop-name">{{ scope.row.shopName }}</div>
                <div class="shop-rating">
                  <el-rate
                    v-model="scope.row.rating"
                    disabled
                    show-score
                    text-color="#ff9900"
                    score-template="{value}">
                  </el-rate>
                </div>
                <div class="shop-sales">月销量: {{ scope.row.monthlySales }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="userId" label="用户ID" width="80"></el-table-column>
        <el-table-column prop="contactPerson" label="联系人" width="100"></el-table-column>
        <el-table-column prop="contactPhone" label="联系电话" width="120"></el-table-column>
        <el-table-column prop="shopAddress" label="店铺地址" width="200" show-overflow-tooltip></el-table-column>
        <el-table-column prop="businessHours" label="营业时间" width="120"></el-table-column>
        <el-table-column prop="status" label="审核状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="businessStatus" label="营业状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.businessStatus === 1 ? 'success' : 'info'">
              {{ scope.row.businessStatus === 1 ? '营业中' : '休息中' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="申请时间" width="180"></el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleViewDetail(scope.row)">查看</el-button>
            <el-button v-if="scope.row.status === 0" type="text" size="small" @click="handleAudit(scope.row, 1)">通过</el-button>
            <el-button v-if="scope.row.status === 0" type="text" size="small" class="danger-btn" @click="handleAudit(scope.row, 2)">拒绝</el-button>
            <el-button v-if="scope.row.status === 1" type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="small" class="danger-btn" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryParams.size"
          :current-page="queryParams.page"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 商家详情对话框 -->
    <el-dialog
      title="商家详情"
      :visible.sync="merchantDetailVisible"
      width="800px">
      <div v-if="currentMerchant" class="merchant-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="商家ID">{{ currentMerchant.id }}</el-descriptions-item>
          <el-descriptions-item label="用户ID">{{ currentMerchant.userId }}</el-descriptions-item>
          <el-descriptions-item label="店铺名称">{{ currentMerchant.shopName }}</el-descriptions-item>
          <el-descriptions-item label="联系人">{{ currentMerchant.contactPerson }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentMerchant.contactPhone }}</el-descriptions-item>
          <el-descriptions-item label="店铺地址">{{ currentMerchant.shopAddress }}</el-descriptions-item>
          <el-descriptions-item label="营业时间">{{ currentMerchant.businessHours }}</el-descriptions-item>
          <el-descriptions-item label="店铺评分">{{ currentMerchant.rating }}</el-descriptions-item>
          <el-descriptions-item label="月销量">{{ currentMerchant.monthlySales }}</el-descriptions-item>
          <el-descriptions-item label="审核状态">
            <el-tag :type="getStatusTagType(currentMerchant.status)">
              {{ getStatusText(currentMerchant.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="营业状态">
            <el-tag :type="currentMerchant.businessStatus === 1 ? 'success' : 'info'">
              {{ currentMerchant.businessStatus === 1 ? '营业中' : '休息中' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ currentMerchant.createTime }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ currentMerchant.updateTime }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="merchant-images">
          <div class="image-item">
            <div class="image-title">店铺Logo</div>
            <div class="image-content">
              <img :src="currentMerchant.shopLogo || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" alt="店铺Logo">
            </div>
          </div>
          <div class="image-item">
            <div class="image-title">营业执照</div>
            <div class="image-content">
              <img :src="currentMerchant.businessLicense || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" alt="营业执照">
            </div>
          </div>
          <div class="image-item">
            <div class="image-title">食品经营许可证</div>
            <div class="image-content">
              <img :src="currentMerchant.foodLicense || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" alt="食品经营许可证">
            </div>
          </div>
        </div>
        
        <div class="merchant-description">
          <div class="description-title">店铺描述</div>
          <div class="description-content">{{ currentMerchant.shopDesc || '暂无描述' }}</div>
        </div>
      </div>
    </el-dialog>
    
    <!-- 审核对话框 -->
    <el-dialog
      :title="auditForm.status === 1 ? '审核通过' : '审核拒绝'"
      :visible.sync="auditDialogVisible"
      width="500px">
      <el-form :model="auditForm" ref="auditForm" label-width="100px">
        <el-form-item v-if="auditForm.status === 2" label="拒绝原因" prop="reason" :rules="[{ required: true, message: '请输入拒绝原因', trigger: 'blur' }]">
          <el-input v-model="auditForm.reason" type="textarea" :rows="4" placeholder="请输入拒绝原因"></el-input>
        </el-form-item>
        <el-form-item v-else>
          <span>确认通过该商家的入驻申请？</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="auditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAudit">确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 编辑商家对话框 -->
    <el-dialog
      title="编辑商家信息"
      :visible.sync="editDialogVisible"
      width="600px">
      <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="120px">
        <el-form-item label="店铺名称" prop="shopName">
          <el-input v-model="editForm.shopName"></el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="editForm.contactPerson"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="editForm.contactPhone"></el-input>
        </el-form-item>
        <el-form-item label="店铺地址" prop="shopAddress">
          <el-input v-model="editForm.shopAddress"></el-input>
        </el-form-item>
        <el-form-item label="营业时间" prop="businessHours">
          <el-input v-model="editForm.businessHours"></el-input>
        </el-form-item>
        <el-form-item label="店铺描述" prop="shopDesc">
          <el-input type="textarea" v-model="editForm.shopDesc" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="营业状态" prop="businessStatus">
          <el-radio-group v-model="editForm.businessStatus">
            <el-radio :label="1">营业中</el-radio>
            <el-radio :label="0">休息中</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEdit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { getMerchantById, updateMerchant, getMerchantList, getMerchantsByStatus } from '@/api/merchant'

export default {
  name: 'MerchantManagement',
  data() {
    return {
      // 当前激活的标签页
      activeTab: 'all',
      // 查询参数
      queryParams: {
        page: 1,
        size: 10,
        shopName: '',
        status: '',
        businessStatus: ''
      },
      // 商家列表
      merchantList: [],
      // 总记录数
      total: 0,
      // 待审核数量
      pendingCount: 0,
      // 加载状态
      loading: false,
      // 当前查看的商家
      currentMerchant: null,
      // 商家详情对话框可见性
      merchantDetailVisible: false,
      // 审核对话框可见性
      auditDialogVisible: false,
      // 审核表单
      auditForm: {
        id: null,
        status: 1,
        reason: ''
      },
      // 编辑对话框可见性
      editDialogVisible: false,
      // 编辑表单
      editForm: {
        id: null,
        shopName: '',
        contactPerson: '',
        contactPhone: '',
        shopAddress: '',
        businessHours: '',
        shopDesc: '',
        businessStatus: 1
      },
      // 编辑表单验证规则
      editRules: {
        shopName: [
          { required: true, message: '请输入店铺名称', trigger: 'blur' }
        ],
        contactPerson: [
          { required: true, message: '请输入联系人', trigger: 'blur' }
        ],
        contactPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        shopAddress: [
          { required: true, message: '请输入店铺地址', trigger: 'blur' }
        ],
        businessHours: [
          { required: true, message: '请输入营业时间', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchMerchantList()
    this.fetchPendingCount()
  },
  methods: {
    // 获取商家列表
    fetchMerchantList() {
      this.loading = true
      
      // 构建查询参数
      const page = this.queryParams.page
      const size = this.queryParams.size
      const shopName = this.queryParams.shopName || undefined
      const status = this.queryParams.status !== '' ? this.queryParams.status : undefined
      const businessStatus = this.queryParams.businessStatus !== '' ? this.queryParams.businessStatus : undefined
      
      // 获取商家列表
      getMerchantList(page, size, shopName, status, businessStatus)
        .then(response => {
          if (response.code === 200) {
            this.merchantList = response.data
            this.total = response.total
          } else {
            this.$message.error(response.message || '获取商家列表失败')
          }
        })
        .catch(error => {
          console.error('获取商家列表失败', error)
          this.$message.error('获取商家列表失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    // 获取待审核商家数量
    fetchPendingCount() {
      // 获取待审核商家列表
      getMerchantsByStatus(0)
        .then(response => {
          if (response.code === 200) {
            this.pendingCount = response.data.length
          }
        })
        .catch(error => {
          console.error('获取待审核商家数量失败', error)
        })
    },
    
    // 处理标签页点击
    handleTabClick(tab) {
      switch (tab.name) {
        case 'all':
          this.queryParams.status = ''
          break
        case 'pending':
          this.queryParams.status = 0
          break
        case 'approved':
          this.queryParams.status = 1
          break
        case 'rejected':
          this.queryParams.status = 2
          break
      }
      this.fetchMerchantList()
    },
    
    // 处理查询
    handleQuery() {
      this.queryParams.page = 1
      this.fetchMerchantList()
    },
    
    // 重置查询
    resetQuery() {
      this.queryParams = {
        page: 1,
        size: 10,
        shopName: '',
        status: this.queryParams.status, // 保持当前标签页的状态筛选
        businessStatus: ''
      }
      this.fetchMerchantList()
    },
    
    // 查看商家详情
    handleViewDetail(row) {
      // 根据API文档 3.2 根据ID获取商家信息
      getMerchantById(row.id)
        .then(response => {
          if (response.code === 200) {
            this.currentMerchant = response.data
            this.merchantDetailVisible = true
          } else {
            this.$message.error(response.message || '获取商家详情失败')
          }
        })
        .catch(error => {
          console.error('获取商家详情失败', error)
          this.$message.error('获取商家详情失败')
        })
    },
    
    // 处理审核
    handleAudit(row, status) {
      this.auditForm = {
        id: row.id,
        status: status,
        reason: ''
      }
      this.auditDialogVisible = true
    },
    
    // 提交审核
    submitAudit() {
      if (this.auditForm.status === 2 && !this.auditForm.reason) {
        this.$message.warning('请输入拒绝原因')
        return
      }
      
      // 根据API文档 3.15 审核商家接口
      axios.post(`/api/merchants/${this.auditForm.id}/audit?status=${this.auditForm.status}&reason=${this.auditForm.reason || ''}`)
        .then(response => {
          if (response.code === 200) {
            const statusText = this.auditForm.status === 1 ? '通过' : '拒绝'
            this.$message.success(`审核${statusText}成功`)
            this.auditDialogVisible = false
            this.fetchMerchantList()
            this.fetchPendingCount()
          } else {
            this.$message.error(response.message || '审核操作失败')
          }
        })
        .catch(error => {
          console.error('审核操作失败', error)
          this.$message.error('审核操作失败')
        })
    },
    
    // 编辑商家
    handleEdit(row) {
      // 根据API文档 3.2 根据ID获取商家信息
      getMerchantById(row.id)
        .then(response => {
          if (response.code === 200) {
            const merchantData = response.data
            this.editForm = {
              id: merchantData.id,
              shopName: merchantData.shopName,
              contactPerson: merchantData.contactPerson,
              contactPhone: merchantData.contactPhone,
              shopAddress: merchantData.shopAddress,
              businessHours: merchantData.businessHours,
              shopDesc: merchantData.shopDesc || '',
              businessStatus: merchantData.businessStatus
            }
            this.editDialogVisible = true
          } else {
            this.$message.error(response.message || '获取商家信息失败')
          }
        })
        .catch(error => {
          console.error('获取商家信息失败', error)
          this.$message.error('获取商家信息失败')
        })
    },
    
    // 提交编辑
    submitEdit() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          // 根据API文档 3.4 更新商家信息
          updateMerchant({
            id: this.editForm.id,
            shopName: this.editForm.shopName,
            shopDesc: this.editForm.shopDesc,
            businessHours: this.editForm.businessHours,
            contactPerson: this.editForm.contactPerson,
            contactPhone: this.editForm.contactPhone,
            shopAddress: this.editForm.shopAddress
          })
            .then(response => {
              if (response.code === 200) {
                // 更新营业状态
                axios.put(`/api/merchants/${this.editForm.id}/business-status?businessStatus=${this.editForm.businessStatus}`)
                  .then(() => {
                    this.$message.success('商家信息更新成功')
                    this.editDialogVisible = false
                    this.fetchMerchantList()
                  })
                  .catch(error => {
                    console.error('更新营业状态失败', error)
                    this.$message.error('更新营业状态失败')
                  })
              } else {
                this.$message.error(response.message || '商家信息更新失败')
              }
            })
            .catch(error => {
              console.error('商家信息更新失败', error)
              this.$message.error('商家信息更新失败')
            })
        } else {
          return false
        }
      })
    },
    
    // 删除商家
    handleDelete(row) {
      this.$confirm(`确认要删除商家"${row.shopName}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 根据API文档 3.14 删除商家接口
        axios.delete(`/api/merchants/${row.id}`)
          .then(response => {
            if (response.code === 200) {
              this.$message.success('删除成功')
              this.fetchMerchantList()
              this.fetchPendingCount()
            } else {
                    this.$message.error(response.message || '删除失败')
            }
          })
          .catch(error => {
            console.error('删除失败', error)
            this.$message.error('删除失败')
          })
      }).catch(() => {
        // 取消删除操作
      })
    },
    
    // 处理每页大小变化
    handleSizeChange(size) {
      this.queryParams.size = size
      this.fetchMerchantList()
    },
    
    // 处理页码变化
    handleCurrentChange(page) {
      this.queryParams.page = page
      this.fetchMerchantList()
    },
    
    // 获取状态标签类型
    getStatusTagType(status) {
      const types = {
        0: 'warning',   // 待审核
        1: 'success',   // 已通过
        2: 'danger'     // 已拒绝
      }
      return types[status] || 'info'
    },
    
    // 获取状态文本
    getStatusText(status) {
      const texts = {
        0: '待审核',
        1: '已通过',
        2: '已拒绝'
      }
      return texts[status] || '未知状态'
    }
  }
}
</script>

<style scoped>
.merchant-management-container {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: bold;
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.badge {
  margin-top: -2px;
}

.merchant-info-cell {
  display: flex;
  align-items: center;
}

.merchant-logo {
  width: 50px;
  height: 50px;
  margin-right: 10px;
}

.merchant-logo img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.merchant-info {
  flex: 1;
}

.shop-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.shop-rating {
  margin-bottom: 5px;
}

.shop-sales {
  font-size: 12px;
  color: #909399;
}

.danger-btn {
  color: #F56C6C;
}

.merchant-detail {
  padding: 10px;
}

.merchant-images {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.image-item {
  width: 32%;
}

.image-title {
  font-weight: bold;
  margin-bottom: 10px;
}

.image-content {
  height: 200px;
  border: 1px solid #eee;
  border-radius: 4px;
  overflow: hidden;
}

.image-content img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.merchant-description {
  margin-top: 20px;
}

.description-title {
  font-weight: bold;
  margin-bottom: 10px;
}

.description-content {
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
  min-height: 80px;
}
</style>